import {delImgUsingPost, updateQuestionBankUsingPost, uploadImgUsingPost} from '@/api/questionBankController';
import {ProColumns, ProTable} from '@ant-design/pro-components';
import {message, Modal} from 'antd';
import {UploadOutlined, DeleteOutlined} from '@ant-design/icons';
import React from 'react';

interface Props {
    oldData?: API.QuestionBank;
    visible: boolean;
    columns: ProColumns<API.QuestionBank>[];
    onSubmit: (values: API.QuestionBankAddRequest) => void;
    onCancel: () => void;
}

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.QuestionBankUpdateRequest) => {
    const hide = message.loading('正在更新');
    try {
        await updateQuestionBankUsingPost(fields);
        hide();
        message.success('更新成功');
        return true;
    } catch (error: any) {
        hide();
        message.error('更新失败，' + error.message);
        return false;
    }
};

/**
 * 更新弹窗
 * @param props
 * @constructor
 */
const UpdateModal: React.FC<Props> = (props) => {
    const {oldData, visible, columns, onSubmit, onCancel} = props;

    if (!oldData) {
        return <></>;
    }

    const handleUploadImg = async (file: any, row: API.QuestionBank, form: any) => {
        const hide = message.loading('正在上传');
        try {
            const {data, code} = await uploadImgUsingPost({questionBankId: row.id as number}, {}, file);
            hide();
            if (code === 0) {
                message.success('上传成功');
                oldData.picture = data as string;
                form.setFieldsValue({picture: data}); // 更新表单中的头像字段
            } else {
                message.error('上传失败');
            }
        } catch (error: any) {
            hide();
            message.error('上传失败，' + error.message);
        }
    };

    const handleDeleteImg = async (row: API.QuestionBank, form: any) => {
        Modal.confirm({
            title: '确认删除头像',
            content: '删除后头像将无法使用，需重新上传',
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                const hide = message.loading('正在删除');
                try {
                    await delImgUsingPost(({img: row.picture as string, questionBankId: row.id as number}));
                    hide();
                    message.success('删除成功');
                    oldData.picture = '';
                    form.setFieldsValue({picture: ''}); // 更新表单中的头像字段
                } catch (error: any) {
                    hide();
                    message.error('删除失败，' + error.message);
                }
            },
            onCancel() {
                console.log('取消删除');
            },
        });
    };

    return (
        <Modal
            destroyOnClose
            title={'更新'}
            open={visible}
            footer={null}
            onCancel={() => {
                onCancel?.();
            }}
        >
            <ProTable
                type="form"
                columns={[
                    {
                        title: '头像',
                        dataIndex: 'picture',
                        valueType: 'text',
                        renderFormItem: (_, {defaultRender, ...rest}, form) => (
                            <div>
                                {oldData?.picture && (
                                    <img src={oldData.picture} alt="avatar" width="64"/>
                                )}
                                <UploadOutlined
                                    style={{cursor: 'pointer', marginLeft: 8}}
                                    onClick={() => {
                                        const input = document.createElement('input');
                                        input.type = 'file';
                                        input.accept = 'image/*';
                                        input.onchange = (e: any) => {
                                            const file = e.target.files[0];
                                            if (file) {
                                                handleUploadImg(file, oldData!, form);
                                            }
                                        };
                                        input.click();
                                    }}
                                />
                                {oldData?.picture && (
                                    <DeleteOutlined
                                        style={{cursor: 'pointer', marginLeft: 8}}
                                        onClick={() => handleDeleteImg(oldData!, form)}
                                    />
                                )}
                            </div>
                        ),
                    },
                    ...columns,
                ]}
                form={{
                    initialValues: oldData,
                }}
                onSubmit={async (values: API.QuestionBankAddRequest) => {
                    const success = await handleUpdate({
                        ...values,
                        id: oldData?.id as any,
                    } as any);
                    if (success) {
                        onSubmit?.(values);
                    }
                }}
            />
        </Modal>
    );
};
export default UpdateModal;
